package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.po.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebFilter(filterName = "logServiceFilter" , urlPatterns = "/*")
public class LogServiceFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    public static final String BACKEND = "/backend";
    public static final String FRONT = "/front";
    public static final String EMPLOYEE_LOGIN = "/employee/login";
    public static final String EMPLOYEE_LOGOUT = "/employee/logout";
    public static final String NOT_NOTLOGIN = "NOTLOGIN";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//     业务： 判断用户是否登录
//        整理思路：用户是否登录从session判断，要明确我只负责后端，页面跳转我不负责
//        那么如果用户没登录我要给用户一个未登录的标识
//        后端不负责页面，所以页面全部放行，拦截controller,controller中URL是以模块作为前缀
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        首先处理放行
        String requestURI = request.getRequestURI();
        System.out.println("filter thread id" + Thread.currentThread().getId());
        if(requestURI.startsWith("BACKEND")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else if(requestURI.startsWith("FRONT")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else if(requestURI.startsWith("EMPLOYEE_LOGIN")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else if(requestURI.startsWith("EMPLOYEE_LOGOUT")){
            filterChain.doFilter(servletRequest,servletResponse);
//            处理不放行 不放行有登录标识 employeeId放行
        }else {
            Long employeeId = (Long)request.getSession().getAttribute("employeeId");
//            if(null == employeeId){
//                ServletOutputStream outputStream = response.getOutputStream();
//                outputStream.write(JSON.toJSONString(R.error("NOT_NOTLOGIN")).getBytes(StandardCharsets.UTF_8));
//            }else{
//                filterChain.doFilter(servletRequest,servletResponse);
//            }
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
